package com.hanxry.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class DemoHandler implements SimpleTemplate<String>, ConcurrentHandler {
    public static void main(String[] args) throws Exception {
        new DemoHandler().run();
    }

    private static final Logger logger = LoggerFactory.getLogger(DemoHandler.class);

    @Override
    public void run() throws Exception {
        new Coordinator(new Context<>(), 10).start(this);
    }

    @Override
    public void production(Context<String> context) throws Exception {
        logger.info("...............Demo 数据生产开始...............");
        // 轮询起始位置
        int index = 0;
        // 步长
        int step = 100;
        // 模拟一个数据集，实际应用时，这个数据是要从数据库查的
        List<String> demoList = new ArrayList<>();
        for (int i = 0; i < 901; i++) {
            demoList.add("字符串" + i);
        }
        while (true) {
            List<String> list = demoList.subList(index, index + step);
            logger.info("Demo数据生产,index={},Results.size={}", index, list.size());
            if (list.isEmpty()) {
                break;
            }
            index += step;

            for (String entity : list) {
                if (!context.offerDataToConsumptionQueue(entity)) {
                    return;
                }
            }

            if (list.size() < step) {
                // 数据构造完成，等下一轮
                break;
            }
        }
        logger.info("...............Demo 数据生产结束...............");
    }

    @Override
    public void consumption(Context<String> context) throws Exception {
        logger.info("...............Demo 数据消费开始...............");
        while (true) {
            String str = context.pollDataFromConsumptionQueue();
            if (str == null)
                break;
            logger.info("Demo数据消费,本条数据编号 id={}", str);
            try {
                // do sth.
                System.out.println("Do Sth.:" + str);
            } catch (Exception e) {
                logger.error("Demo数据消费出错,本条数据编号 id={}", str, e);
                try {
                    System.out.println("记录出错次数");
                    // 出错了，要干点什么
//                    pushMapper.updateForExceptionById(push.getId(), new Date());
                } catch (Exception e1) {
                    logger.error("记录Demo数据消费失败次数失败...... str.id={}", str, e1);
                    return;
                }
            }
        }
        logger.info("...............Demo 数据消费结束...............");
    }
}
